package com.rockcent.common.utils;

import jxl.CellView;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.jxls.area.Area;
import org.jxls.builder.AreaBuilder;
import org.jxls.builder.xls.XlsCommentAreaBuilder;
import org.jxls.common.CellRef;
import org.jxls.common.Context;
import org.jxls.transform.Transformer;
import org.jxls.transform.poi.PoiContext;
import org.jxls.transform.poi.PoiTransformer;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangjh on 2016/12/28.
 */
public class ExcelCreateUtils<T> {
    private static ExcelCreateUtils ourInstance = new ExcelCreateUtils();

    public static ExcelCreateUtils getInstance() {
        return ourInstance;
    }

    private static final Logger logger = LoggerFactory.getLogger(ExcelCreateUtils.class);

    private ExcelCreateUtils() {
    }


    /**
     * 创建文件
     *
     * @param data         数据
     * @param dataName     key
     * @param fileName     文件名
     * @param ctxPath      文件存放路径
     * @param templatePath 模板路径
     * @return 新文件具体地址
     * @throws IOException            IOException
     * @throws InvalidFormatException InvalidFormatException
     */
    public String create(T data, String dataName, String fileName, String ctxPath, String templatePath) throws IOException, InvalidFormatException {
        String downLoadPath = ctxPath + File.separator + fileName;
        //生成生成指示单
        OutputStream os = new FileOutputStream(downLoadPath);
        org.springframework.core.io.Resource fileRource = new ClassPathResource(templatePath);
        InputStream is = fileRource.getInputStream();
        Transformer transformer = PoiTransformer.createTransformer(is, os);
        AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
        List<Area> xlsAreaList = areaBuilder.build();
        Area xlsArea = xlsAreaList.get(0);
        Context context = new PoiContext();
        context.putVar(dataName, data);
//            xlsArea.applyAt(new CellRef("Sheet2!A1"), context);
        xlsArea.applyAt(new CellRef("Sheet1!A1"), context);
        xlsArea.processFormulas();
        transformer.write();
        return downLoadPath;
    }


    /**
     * @param data         数据集合
     * @param dataName     数据别名
     * @param fileName     文件名
     * @param response     HttpServletResponse
     * @param templatePath 模板路径
     * @throws IOException            IOException
     * @throws InvalidFormatException InvalidFormatException
     */
    public void create(T data, String dataName, String fileName, HttpServletResponse response, String templatePath) throws IOException, InvalidFormatException {
        InputStream is = null;
        OutputStream os = null;
        try {
            //            response.setContentType("multipart/form-data");
//            response.setContentType("application/x-msdownload;charset=utf-8");
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//            response.setContentType("application/vnd.ms-excel;charset=utf-8");   //这个是可用的
            //            response.setContentType("application/octet-stream;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");   //这个是可用的
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            os = response.getOutputStream();
            org.springframework.core.io.Resource fileRource = new ClassPathResource(templatePath);
            is = fileRource.getInputStream();
            // 关闭输出流 
            Context context = new Context();
            context.putVar("idata", data);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.flush();
            os.close();
        } finally {
            // 关闭输出流
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }


    }

    public void  createDynamic(Map<String, Object> data, String dataName, String fileName, HttpServletResponse response, String templatePath, String objectProps) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");   //这个是可用的
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            os = response.getOutputStream();
            org.springframework.core.io.Resource fileRource = new ClassPathResource(templatePath);
            is = fileRource.getInputStream();
            // 关闭输出流 
            Context context = new Context();
            context.putVar("idata", data);
            JxlsHelper.getInstance().processGridTemplateAtCell(is, os, context, objectProps, "Sheet1!A1");
//            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.flush();
            os.close();
        } finally {
            // 关闭输出流
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }


    }
}
